package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.qf.pojo.Shop;
import com.qf.service.ShopService;
import com.qf.service.impl.ShopServiceImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 商品管理的控制器
 */
@WebServlet("/findAllShop")
public class ShopController extends HttpServlet {

    //声明ShopService
    private ShopService shopService ;
    //提供无参构造方法
    public ShopController(){
        //读取spring的核心配置文件
        ClassPathXmlApplicationContext applicationContext
                =new ClassPathXmlApplicationContext("spring-config.xml") ;
        //获取ShopService接口子实现类对象--->交给Spring
        //@Service:没有给定标识,所以按照接口类型创建子实现类对象
         shopService =  applicationContext.getBean(ShopService.class);
        System.out.println(shopService); //打印业务层对象的地址

    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //处理中文乱码:响应的乱码
        response.setContentType("text/html;charset=utf-8");
        //调用业务接口

        List<Shop> shopList = shopService.getAllShop();

        //导入jar包:fastJson也是一个json解析工具
        //shopList---转换成json格式
        //解析器JSONObject的方法toJSONString(Object obj)
        String jsonStr = JSONObject.toJSONString(shopList);
        System.out.println(jsonStr);
        //响应给浏览器
        response.getWriter().write(jsonStr);

    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);

    }
}
